package com.eric.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.eric.domain.dto.UserDto;
import com.eric.domain.po.Permission;
import com.eric.domain.po.Role;
import com.eric.domain.po.User;
import com.eric.domain.vo.UserVo;
import com.eric.mapper.UserMapper;
import com.eric.service.UserService;
import com.eric.utils.RegexUtils;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-02-12
 */
@Service
public class UserServiceImpl extends MPJBaseServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Object getOneById(Integer id) {
        User user = getById(id);
        return BeanUtil.copyProperties(user, UserVo.class);
    }

    @Override
    public SaResult doLoginService(Map<String, String> userPw, HttpServletRequest request) {
        if (userPw != null&& !userPw.isEmpty()) {
            String account = userPw.get("account");
            String pw = userPw.get("pw");
//        判断用户名的正则表达式，错误返回“用户名有误”
            if (RegexUtils.isLoginUserInvalid(account)) {
                return SaResult.error("用户名有误！");
            }
//        从数据库中通过“loginname”查找相应记录
            User loginUser = query().eq("loginname", account).one();
//        如果对象为空，表示数据库空白，返回错误
            if (BeanUtil.isEmpty(loginUser)) {
                return SaResult.error("用户不存在！");
            }
//       通过BCrypt的checkpw方法，校验传进来的密码====================================这里有问题
//        默认密码是1234
            if (!BCrypt.checkpw(pw, loginUser.getPassword())) {
                return SaResult.error("密码错误！");
            }
//        login的id使用数据库User的id,记住我模式打开
            StpUtil.login(loginUser.getId(),true);
//        把查询到的user转发成UserDto
//        UserDto userDto = BeanUtil.copyProperties(loginUser, UserDto.class);
//      获取到token信息
            String token = StpUtil.getTokenValue();
//      把token的value返回到前端
            return SaResult.data(token);
        }

        return SaResult.error();

    }

    @Override
    public SaResult saveOne(User newUser, MultipartFile file, HttpServletRequest req) {

        String userName = newUser.getLoginname();
//        根据前端传进来的对象，查询数据库中有没有相同登录名的数据存在
        User userInDb = query().eq(true, "loginname", userName).one();
        if (!BeanUtil.isEmpty(userInDb)){
            return SaResult.error("用户已存在");
        }
        User user = BeanUtil.copyProperties(newUser, User.class);
//        加密密码(还加了盐)
        user.setPassword(BCrypt.hashpw(newUser.getPassword(),BCrypt.gensalt()));

//        新注册用户，默认是normal角色，id是4，共5种
//        MPJLambdaWrapper<UR>wrapper=new MPJLambdaWrapper<>();
//        List<String>roles= Arrays.asList("admin","superadmin","manager","normal","visit");
//        String jsonStr = JSONUtil.toJsonStr(roles);
//        user.setRealname(jsonStr);
//
//        boolean save = save(user);
//        return SaResult.data(save);


        return null;

    }

    @Override

    public List<String> getUserPermissionById(int userId) {
        MPJLambdaWrapper<User> wrapper=new MPJLambdaWrapper<User>()
                .selectAll(User.class)
                .selectAssociation(Permission.class,UserDto::getPermission)
                .eq(User::getId,userId)
                .leftJoin(Permission.class,Permission::getId,User::getPermissionid);

        UserDto userDto = selectJoinOne(UserDto.class, wrapper);
//        获取到permissions的json数据
        String permissions = userDto.getPermission().getPermissions();
//        转换层JSONArray对象
        JSONArray objects = JSONUtil.parseArray(permissions);
//        把JSONArray对象转换为string 集合
        List<String> permissionList = objects.toList(String.class);
        System.out.println(permissionList);
        return permissionList;
    }

    @Override
    public List<String> getUserRolesByUserId(int userId) {
        MPJLambdaWrapper<User>wrapper=new MPJLambdaWrapper<User>()
                .selectAll(User.class)
                .selectAssociation(Role.class,UserDto::getRole)
                .eq(User::getId,userId)
                .leftJoin(Role.class,Role::getId,User::getRoleid);
        UserDto userDto = selectJoinOne(UserDto.class, wrapper);
        String roles = userDto.getRole().getRoles();
        JSONArray objects = JSONUtil.parseArray(roles);
        List<String> roleList = objects.toList(String.class);
        System.out.println(roleList);
        return roleList;
    }

}
